package com.xinz.protocal;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import com.xinz.protocal.client.InvokeConnector;
import com.xinz.protocal.client.RemoteInvoker;
import com.xinz.protocal.client.SimpleHttpClient;
import com.xinz.protocal.client.SimpleSocketClient;
import com.xinz.protocal.config.ConfigFactory;
import com.xinz.protocal.server.NativeInvoker;

public abstract class SrmiClient extends Thread implements InvokeConnector{

	protected RemoteInvoker remoteInvoker;
	
	protected NativeInvoker nativeInvoker;
	
	protected Session session;
	
	protected SrmiClient(ConfigFactory factory) {
		session = new Session(new NativeInterfaceProvider());
		remoteInvoker = new RemoteInvoker(factory, this);
		session.initInvoker(remoteInvoker);
		nativeInvoker = new NativeInvoker(factory);
	}
	
	public static SrmiClient createHttp(String url, ConfigFactory factory) {
		try {
			return new SimpleHttpClient(new URL(url), factory);
		}
		catch(MalformedURLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static SrmiClient createSocket(String ip, int port, ConfigFactory factory) {
		try {
			return new SimpleSocketClient(ip, port, factory);
		}
		catch(IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public Session getSession() {
		return session;
	}

	/***
	 * 连接到远程服务器
	 */
	public synchronized void connect() {
		start();
	}
	
	/**
	 * 获取远程实现
	 * @param clazz
	 * @return
	 */
	public <T> T getImplement(Class<T> clazz){
		return remoteInvoker.getImplement(clazz);
	}
	
	@Override
	public abstract Buffer request(Buffer request) throws IOException;

}
